package com.yolo.yolorpc.proxy;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.yolo.yolorpc.model.RpcRequest;
import com.yolo.yolorpc.model.RpcResponse;
import com.yolo.yolorpc.serializer.JdkSerializer;
import com.yolo.yolorpc.serializer.Serializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Program RPC
 * @description 服务代理（JDK动态代理）
 * @author yolo
 * @create 2025-04-21 18:07
 **/
public class ServiceProxy implements InvocationHandler {

    /**
     * @descript 调用代理
     * @author yolo
     * @date 2025/4/21 18:08
     * @param proxy
     * @param method
     * @param args
     * @return Object
     **/
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 指定序列化器
        Serializer serializer = new JdkSerializer();

        // 构造请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serverName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        try {
            // 序列化
            byte[] serialized = serializer.serialize(rpcRequest);
            byte[] body;
            // 发送请求
            // TODO:注意这里的地址被硬编码了（需要用服务中心和服务发现机制解决）
            try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                    .body(serialized)
                    .execute()) {
                body = httpResponse.bodyBytes();
            }
                // 反序列化
                RpcResponse result = serializer.deserialize(body, RpcResponse.class);
                return result.getData();

        } catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }
}
